package com.visionet.school.app.web.common.utils;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.*;
import java.security.spec.InvalidKeySpecException;

/**
 * Token Utility Class.
 */
public final class EncryptUtils {
    private static final Logger logger = LoggerFactory.getLogger(EncryptUtils.class);

    // cipher key
    private static final String CIPHER_KEY = "cxj_0987654321";

    // 算法名称
    public static final String KEY_ALGORITHM = "DES";

    // des cipher key
    private static final String DES_CIPHER_KEY = "cxj_20151116";

    // 算法名称/加密模式/填充方式
    // DES共有四种工作模式-->>ECB：电子密码本模式、CBC：加密分组链接模式、CFB：加密反馈模式、OFB：输出反馈模式
    public static final String CIPHER_ALGORITHM = "DES/ECB/NoPadding";

    /**
     * default private constructor
     */
    private EncryptUtils() {

    }

    /**
     * Encode a string using MD5 and return the resulting encrypted password. If
     * exception, the plain credentials string is returned
     *
     * @param inputStr InputStr or other credentials to use in authenticating this
     *                 username
     * @return encypted password based on the algorithm.
     */
    public static String encryptString(String inputStr) {
        return encryptString(inputStr, "MD5");
    }

    /**
     * Encode a string using algorithm and return the resulting encrypted
     * password. If exception, the plain credentials string is returned
     *
     * @param token     Token or other credentials to use in authenticating this
     *                  username
     * @param algorithm Algorithm used to do the digest
     * @return encypted password based on the algorithm.
     */
    private static String encryptString(String token, String algorithm) {
        byte[] unencodedToken = token.getBytes();

        MessageDigest md;

        try {
            // first create an instance, given the provider
            md = MessageDigest.getInstance(algorithm);
        } catch (Exception e) {
            logger.error("Exception: " + e);

            return token;
        }

        md.reset();

        // call the update method one or more times
        // (useful when you don't know the size of your data, eg. stream)
        md.update(unencodedToken);

        // now calculate the hash
        byte[] encodedToken = md.digest();

        StringBuffer buf = new StringBuffer();

        for (int i = 0; i < encodedToken.length; i++) {
            if (((int) encodedToken[i] & 0xff) < 0x10) {
                buf.append("0");
            }

            buf.append(Long.toString((int) encodedToken[i] & 0xff, 16));
        }

        return buf.toString();
    }

    /**
     * verify if encryption token is valid.
     *
     * @param plainText  - plain text
     * @param cipherText - cipher text
     * @return true if token is valid,false if token is invalid.
     */
    public static boolean verifyEncryptionToken(String plainText,
                                                String cipherText) {
        if (StringUtils.isNotEmpty(cipherText)
                && StringUtils.isNotEmpty(plainText)) {
            return cipherText.equals(encryptString(CIPHER_KEY + plainText));
        } else {
            return false;
        }
    }

    /**
     * get encryption token
     *
     * @param plainText - plain text
     * @return encryption token string
     * @Date : 2011-3-23
     */
    public static String getEncryptionToken(String plainText) {
        return encryptString(CIPHER_KEY + plainText);
    }

    /**
     * 生成密钥key对象
     *
     * @param keyStr 密钥字符串
     * @return 密钥对象
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws Exception
     */
    private static SecretKey keyGenerator(String keyStr) throws Exception {

        byte input[] = keyStr.getBytes();
        DESKeySpec desKey = new DESKeySpec(input);
        // 创建一个密匙工厂，然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
        SecretKey securekey = keyFactory.generateSecret(desKey);
        return securekey;
    }

    /**
     * 加密数据
     *
     * @param data 待加密数据
     * @return 加密后的数据
     */
    public static String desEncrypt(String data) throws Exception{
        Key deskey = keyGenerator(DES_CIPHER_KEY);

        // 实例化Cipher对象，它用于完成实际的加密操作
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        SecureRandom random = new SecureRandom();
        // 初始化Cipher对象，设置为加密模式
        cipher.init(Cipher.ENCRYPT_MODE, deskey, random);

        // 执行加密操作。加密后的结果通常都会用Base64编码进行传输
        return Base64.encodeBase64String(cipher.doFinal(data.getBytes()));
    }

    /**
     * 解密数据
     *
     * @param data 待解密数据
     * @return 解密后的数据
     */
    public static String desDecrypt(String data) {

        try {
            Key deskey = keyGenerator(DES_CIPHER_KEY);

            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            // 初始化Cipher对象，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, deskey);

            // 执行解密操作
            return new String(cipher.doFinal(Base64.decodeBase64(data)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] params) {
//        System.out.println(Md5Util32.md5("123456"));
        System.out.println(getEncryptionToken("123456"));
//        System.out.println(desEncrypt("e10adc3949ba59abbe56e057f20f883e"));
        System.out.println(desDecrypt("m2xnLbJMThIM2yNxzKhAijX3hQWPad1GlKtuaIXlsRI="));
//
//        long timestamp = DateUtil.getCurrentDate().getTime();
//        String xx=timestamp+ KeyWord.SYS_CODE_CHEXIANG.toLowerCase();
//        String accessToken= Md5Util32.md5(xx);
//        System.out.println(timestamp);
////        System.out.println(xx);
//        System.out.println(accessToken);


    }
}

